package com.tywj.buscustomerapp.view.activity;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.CityBean;
import com.tywj.buscustomerapp.utils.RecyclerItemClickListener;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.utils.myadapter.CommonRcvAdapter;
import com.tywj.buscustomerapp.utils.myadapter.item.AdapterItem;
import com.tywj.buscustomerapp.view.item.CityItem;
import com.umeng.analytics.MobclickAgent;

import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 *
 * create by Taylor
 * 20180517
 * 需解决app每次打开才重新获取数据
 */
public class ChooseCityActivity extends BaseActivity {
    @BindView(R.id.head_title)
    TextView headtite;
    @BindView(R.id.head_left)
    ImageView back;
    @BindView(R.id.local_city)
    TextView localCity;
    @BindView(R.id.city_recycler)
    RecyclerView recyclerView;
    private CommonRcvAdapter<CityBean> adapter;
    private List<CityBean> citys = new ArrayList<>();
    @Override
    protected int getContentId() {
        return R.layout.activity_choose_city;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        headtite.setText(R.string.title_city);
        adapter = new CommonRcvAdapter<CityBean>(citys) {
            @NonNull
            @Override
            public AdapterItem createItem(Object type) {
                return new CityItem();
            }
        };
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        super.initData();

        getCitys();
    }

    private void getCitys() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String msg = WebServicrUtils.getInstance().getCityInWebService();
                    InputStream in_nocode = new ByteArrayInputStream(msg.getBytes("UTF-8"));
                    List<CityBean>list = WebServicrUtils.getInstance().getCitys(in_nocode);
                    if (list!=null && list.size()>0){
                        Message message = Message.obtain();
                        message.what = 2001;
                        message.obj = list;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==2001){
                List<CityBean> list = (List<CityBean>) msg.obj;
                citys.addAll(list);
                adapter.setData(citys);
                adapter.notifyDataSetChanged();
                startGetLocation();
            }
        }
    };

    /**
     * 定位
     */
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //初始化AMapLocationClientOption对象
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            String mapCity = aMapLocation.getCity();
            localCity.setText(mapCity);
            if (citys!=null && citys.size()>0){
                for (int i = 0; i < citys.size(); i++) {
                    if (mapCity.equals(citys.get(i).getCityName())){
                        citys.set(0, citys.get(i));
                    }
                }
//
//                if (citys.get(0).getCityId()==null){
//                    CityBean cityBean = citys.get(0);
//                    cityBean.setCityId(null);
//                    cityBean.setCityName(mapCity+"暂未开通");
//                    citys.set(0,cityBean);
//                }
                adapter.setData(citys);
                adapter.notifyItemChanged(0);
            }else{
//                CityBean cityBean = citys.get(0);
//                cityBean.setCityId(null);
//                cityBean.setCityName(mapCity+"暂未开通");
//                citys.set(0, cityBean);
            }
        }
    };
    public void startGetLocation(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setLocationCacheEnable(false);//关闭定位缓存
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position==0 &&
                        (citys.get(0).getCityName().contains("暂未开通")||citys.get(0).getCityName().equals("定位中...") ||citys.get(0).getCityName().equals("")
                        )){

                }else {
                    Intent mIntent = new Intent();
                    mIntent.putExtra("city", citys.get(position));
                    setResult(1002, mIntent);
                    finish();
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        }));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler!=null)
            handler.removeMessages(2001);
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("城市选择");
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("城市选择");
        MobclickAgent.onPause(this);
    }
}
